/*
 * contrib/btree_gist/btree_uuid.c
 */
#include "postgres.h"

#include "btree_gist.h"
#include "btree_utils_num.h"
#include "port/pg_bswap.h"
#include "utils/uuid.h"

typedef struct
{
	pg_uuid_t	lower,
				upper;
} uuidKEY;


/*
 * UUID 操作
 */
PG_FUNCTION_INFO_V1(gbt_uuid_compress);
PG_FUNCTION_INFO_V1(gbt_uuid_fetch);
PG_FUNCTION_INFO_V1(gbt_uuid_union);
PG_FUNCTION_INFO_V1(gbt_uuid_picksplit);
PG_FUNCTION_INFO_V1(gbt_uuid_consistent);
PG_FUNCTION_INFO_V1(gbt_uuid_penalty);
PG_FUNCTION_INFO_V1(gbt_uuid_same);


static int fc_uuid_internal_cmp(const pg_uuid_t *fc_arg1, const pg_uuid_t *fc_arg2)
{
	return memcmp(fc_arg1->data, fc_arg2->data, UUID_LEN);
}

static bool fc_gbt_uuidgt(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	return fc_uuid_internal_cmp((const pg_uuid_t *) fc_a, (const pg_uuid_t *) fc_b) > 0;
}

static bool fc_gbt_uuidge(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	return fc_uuid_internal_cmp((const pg_uuid_t *) fc_a, (const pg_uuid_t *) fc_b) >= 0;
}

static bool fc_gbt_uuideq(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	return fc_uuid_internal_cmp((const pg_uuid_t *) fc_a, (const pg_uuid_t *) fc_b) == 0;
}

static bool fc_gbt_uuidle(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	return fc_uuid_internal_cmp((const pg_uuid_t *) fc_a, (const pg_uuid_t *) fc_b) <= 0;
}

static bool fc_gbt_uuidlt(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	return fc_uuid_internal_cmp((const pg_uuid_t *) fc_a, (const pg_uuid_t *) fc_b) < 0;
}

static int fc_gbt_uuidkey_cmp(const void *fc_a, const void *fc_b, FmgrInfo *fc_flinfo)
{
	uuidKEY    *fc_ia = (uuidKEY *) (((const Nsrt *) fc_a)->t);
	uuidKEY    *fc_ib = (uuidKEY *) (((const Nsrt *) fc_b)->t);
	int			fc_res;

	fc_res = fc_uuid_internal_cmp(&fc_ia->lower, &fc_ib->lower);
	if (fc_res == 0)
		fc_res = fc_uuid_internal_cmp(&fc_ia->upper, &fc_ib->upper);
	return fc_res;
}


static const gbtree_ninfo tinfo =
{
	gbt_t_uuid,
	UUID_LEN,
	32,							/* sizeof(gbtreekey32) */
	fc_gbt_uuidgt,
	fc_gbt_uuidge,
	fc_gbt_uuideq,
	fc_gbt_uuidle,
	fc_gbt_uuidlt,
	fc_gbt_uuidkey_cmp,
	NULL
};


/**************************************************
 * uuid 操作
 **************************************************/


Datum gbt_uuid_compress(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	GISTENTRY  *fc_retval;

	if (fc_entry->leafkey)
	{
		char	   *fc_r = (char *) palloc(2 * UUID_LEN);
		pg_uuid_t  *fc_key = DatumGetUUIDP(fc_entry->key);

		fc_retval = palloc(sizeof(GISTENTRY));

		memcpy((void *) fc_r, (void *) fc_key, UUID_LEN);
		memcpy((void *) (fc_r + UUID_LEN), (void *) fc_key, UUID_LEN);
		gistentryinit(*fc_retval, PointerGetDatum(fc_r),
					  fc_entry->rel, fc_entry->page,
					  fc_entry->offset, false);
	}
	else
		fc_retval = fc_entry;

	PG_RETURN_POINTER(fc_retval);
}

Datum gbt_uuid_fetch(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);

	PG_RETURN_POINTER(gbt_num_fetch(fc_entry, &tinfo));
}

Datum gbt_uuid_consistent(PG_FUNCTION_ARGS)
{
	GISTENTRY  *fc_entry = (GISTENTRY *) PG_GETARG_POINTER(0);
	pg_uuid_t  *fc_query = PG_GETARG_UUID_P(1);
	StrategyNumber fc_strategy = (StrategyNumber) PG_GETARG_UINT16(2);

	/* Oid		subtype = PG_GETARG_OID(3); */
	bool	   *fc_recheck = (bool *) PG_GETARG_POINTER(4);
	uuidKEY    *fc_kkk = (uuidKEY *) DatumGetPointer(fc_entry->key);
	GBT_NUMKEY_R fc_key;

	/* 由此函数服务的所有案例都是精确的 */
	*fc_recheck = false;

	fc_key.lower = (GBT_NUMKEY *) &fc_kkk->lower;
	fc_key.upper = (GBT_NUMKEY *) &fc_kkk->upper;

	PG_RETURN_BOOL(gbt_num_consistent(&fc_key, (void *) fc_query, &fc_strategy,
									  GIST_LEAF(fc_entry), &tinfo,
									  fcinfo->flinfo));
}

Datum gbt_uuid_union(PG_FUNCTION_ARGS)
{
	GistEntryVector *fc_entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
	void	   *fc_out = palloc(sizeof(uuidKEY));

	*(int *) PG_GETARG_POINTER(1) = sizeof(uuidKEY);
	PG_RETURN_POINTER(gbt_num_union((void *) fc_out, fc_entryvec, &tinfo, fcinfo->flinfo));
}

/*
 * 将 uuid 转换为 "double" 值以估算范围的大小。
 */
static double fc_uuid_2_double(const pg_uuid_t *fc_u)
{
	uint64		fc_uu[2];
	const double fc_two64 = 18446744073709551616.0;	/* 2^64 */

	/* 源数据可能没有适当对齐，因此需要复制 */
	memcpy(fc_uu, fc_u->data, UUID_LEN);

	/*
	 * uuid 值应视为大端数字，因为这与 memcmp 比较它们的方式相对应。
	 * 在小端机器上，交换每个半部分的字节，以便我们可以使用本机 uint64 运算。
	 */
#ifndef WORDS_BIGENDIAN
	fc_uu[0] = pg_bswap64(fc_uu[0]);
	fc_uu[1] = pg_bswap64(fc_uu[1]);
#endif

	/*
	 * 2^128 约为 3.4e38，理论上可能超出 "double" 的范围
	 * （POSIX 只要求 1e37）。为了避免任何溢出风险，
	 * 将小数点放在两个半部分之间，而不是将 uuid 值视为 128 位整数。
	 */
	return (double) fc_uu[0] + (double) fc_uu[1] / fc_two64;
}

Datum gbt_uuid_penalty(PG_FUNCTION_ARGS)
{
	uuidKEY    *fc_origentry = (uuidKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
	uuidKEY    *fc_newentry = (uuidKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
	float	   *fc_result = (float *) PG_GETARG_POINTER(2);
	double		fc_olower,
				fc_oupper,
				fc_nlower,
				fc_nupper;

	fc_olower = fc_uuid_2_double(&fc_origentry->lower);
	fc_oupper = fc_uuid_2_double(&fc_origentry->upper);
	fc_nlower = fc_uuid_2_double(&fc_newentry->lower);
	fc_nupper = fc_uuid_2_double(&fc_newentry->upper);

	penalty_num(fc_result, fc_olower, fc_oupper, fc_nlower, fc_nupper);

	PG_RETURN_POINTER(fc_result);
}

Datum gbt_uuid_picksplit(PG_FUNCTION_ARGS)
{
	PG_RETURN_POINTER(gbt_num_picksplit((GistEntryVector *) PG_GETARG_POINTER(0),
										(GIST_SPLITVEC *) PG_GETARG_POINTER(1),
										&tinfo, fcinfo->flinfo));
}

Datum gbt_uuid_same(PG_FUNCTION_ARGS)
{
	uuidKEY    *fc_b1 = (uuidKEY *) PG_GETARG_POINTER(0);
	uuidKEY    *fc_b2 = (uuidKEY *) PG_GETARG_POINTER(1);
	bool	   *fc_result = (bool *) PG_GETARG_POINTER(2);

	*fc_result = gbt_num_same((void *) fc_b1, (void *) fc_b2, &tinfo, fcinfo->flinfo);
	PG_RETURN_POINTER(fc_result);
}
